const WebSocket = require('ws');

class ChatHandler {
    constructor() {
        this.chatWss = new WebSocket.Server({ noServer: true });
        this.setupChatHandler();
    }

    setupChatHandler() {
        this.chatWss.on('connection', (ws, request) => {
            console.log('聊天客户端已连接聊天服务器');
            ws.wsType = 'chat'; //设置wsType为chat

            ws.on('message', (message) => { //处理消息
                try {
                    const data = JSON.parse(message);
                    this.handleChatMessage(ws, data);
                } catch (error) {
                    ws.send(JSON.stringify({ type: 'error', message: '消息格式错误' }));
                }
            });

            ws.on('close', (code, reason) => { //处理断开连接
                console.log(`聊天客户端断开连接: ${code} - ${reason}`);
                this.handleClientDisconnect(ws);
            });

            ws.send(JSON.stringify({ type: 'welcome', message: '欢迎来到聊天室' })); //发送欢迎消息 

            // 定时发送消息
            const intervalId = setInterval(() => {
                if (ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({ type: 'message', message: '这是一条定时消息' }));
                } else {
                    clearInterval(intervalId);
                }
            }, 5000);

            // 保存定时器ID，以便在断开时清理
            ws.chatIntervalId = intervalId;
        });
    }

    // 处理聊天消息
    handleChatMessage(ws, data) {
        switch (data.type) {
            case 'sendMessage': //如果是用户发送消息，广播消息
                this.broadcastMessage({
                    type: 'newMessage',
                    user: data.user || '匿名用户', //读取到用户名
                    message: data.message, //读取到消息
                    timestamp: new Date().toISOString() //读取到当前时间
                });
                break;
            case 'joinRoom': //如果是用户加入房间
                ws.room = data.room || 'default';
                ws.send(JSON.stringify({ 
                    type: 'roomJoined', 
                    room: ws.room,
                    message: `已加入房间: ${ws.room}`
                }));
                break;
            case 'leaveRoom': //如果是用户离开房间
                ws.room = null;
                ws.send(JSON.stringify({ 
                    type: 'roomLeft', 
                    message: '已离开房间'
                }));
                break;
            default: //如果是未知的消息类型，发送错误消息
                ws.send(JSON.stringify({ type: 'error', message: '未知的聊天消息类型' }));
        }
    }

    // 处理客户端断开连接
    handleClientDisconnect(ws) {
        // 清理定时器
        if (ws.chatIntervalId) {
            clearInterval(ws.chatIntervalId);
        }
        
        // 通知其他用户该用户已离开
        if (ws.userName) {
            this.broadcastMessage({ //广播消息
                type: 'userLeft',
                user: ws.userName,
                message: `${ws.userName} 离开了聊天室`,
                timestamp: new Date().toISOString()
            });
        }
    }

    // 广播消息
    broadcastMessage(message, filter = null) { //参数：1、消息内容，2、过滤器函数
        this.chatWss.clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                if (filter && !filter(client)) {
                    return;
                }
                client.send(JSON.stringify(message));
            }
        });
    }

    getServer() {
        return this.chatWss;
    }
}

module.exports = ChatHandler;